#include"index.hpp"

#include<algorithm>
#include<jsoncpp/json/json.h>
namespace ns_searcher{

    class Searcher{
        ns_index::Index *index;
        public:
        Searcher(){}
        ~Searcher(){}
        public:
        void InitSearcher(const std::string &input)
        {
            //获取index对象
            index=ns_index::Index::GetInstance();
            index->BuildIndex(input);
            //根据index对象建立索引
        }
        
        void Search(const std::string &query,std::string *json_string){
	cppjieba::Jieba jieba("./dict/jieba.dict.utf8",
"./dict/hmm_model.utf8",
"./dict/user.dict.utf8",
"./dict/idf.utf8",
"./dict/stop_words.utf8");
            //分词
            std::vector<std::string> words;
            //ns_index::Jieba::Cutword();
	jieba.Cut(query,words, true);
            //搜索
            std::vector<ns_index::InverterElem> Alllist;
            for(std::string &s:words){
                boost::to_lower(s);
                ns_index::InvertedList * invertedlis = index->getInvertedList(s);
                if(nullptr==invertedlis){
                    continue;
                }
                Alllist.insert(Alllist.end(),invertedlis->begin(),invertedlis->end());
        
            }
            //合并排序
            std::sort(Alllist.begin(),Alllist.end(),[](const ns_index::InverterElem &a, const ns_index::InverterElem &b){
               return a.weight>b.weight;
            });
            //构建——json串 jsoncpp库
            Json::Value root;
            for(auto &item:Alllist){
               ns_index::DocInfo*doc= index->getfile( item.doc_id);
                if(nullptr==doc){
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desc"] = doc->contents.substr(0,50);
                elem["url"] = doc->url;
                root.append(elem);
            }
            Json::StyledWriter writer;
            *json_string = writer.write(root);
        }

    };


}
